package city.spring.modules.material.controller;

import city.spring.modules.material.entity.MaterialreceiptEntity;
import city.spring.modules.material.service.MaterialSettingService;
import city.spring.modules.material.service.MaterialreceiptService;
import city.spring.modules.material.vo.MaterialreceiptVO;
import city.spring.modules.system.service.OrganizationService;
import city.spring.modules.system.service.UserService;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.NonNull;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.data.web.SortDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Controller：领用申请表
 *
 * @author 谢金婷
 * @date 2020-06-19 11:28:23
 */
@RestController
@RequestMapping("/receipt")
public class MaterialreceiptController extends ApiController {
    private final MaterialreceiptService receiptService;
    private final UserService userService;
    private final OrganizationService organizationService;
    private final MaterialSettingService materialSettingService;
    /**
     * 实体类可排序字段
     */
    private final List<SFunction<MaterialreceiptEntity, ?>> entityOrderFields;

    public MaterialreceiptController(MaterialreceiptService receiptService, UserService userService, OrganizationService organizationService, MaterialSettingService materialSettingService) {
        this.receiptService = receiptService;
        this.userService = userService;
        this.organizationService = organizationService;
        this.materialSettingService = materialSettingService;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(MaterialreceiptEntity::getId);
        entityOrderFields.add(MaterialreceiptEntity::getReceipter);
        entityOrderFields.add(MaterialreceiptEntity::getDepartment);
        entityOrderFields.add(MaterialreceiptEntity::getApplicationdate);
        entityOrderFields.add(MaterialreceiptEntity::getApplication);
        entityOrderFields.add(MaterialreceiptEntity::getDeliveryStatus);
    }

    /**
     * 获取全部的 <strong>领用申请表</strong> 列表
     */
    @GetMapping("all")
    public Object listAll(@PageableDefault(sort = {"gmtCreate"}) Pageable pageable, MaterialreceiptEntity entity) {
        LambdaQueryChainWrapper<MaterialreceiptEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

    /**
     * 分页获取 <strong>领用申请表</strong> 列表
     *
     * @param pageable 分页参数信息
     */
    @GetMapping
    public Object list(@PageableDefault @SortDefault.SortDefaults({@SortDefault(sort = "id", direction = Sort.Direction.DESC)}) Pageable pageable, MaterialreceiptVO entity, Date[] applicationdate) {

        QueryWrapper<? extends MaterialreceiptEntity> queryWrapper = buildQuery(entity);
        if (applicationdate != null && applicationdate.length == 2) {
            queryWrapper.ge("t1.applicationdate", applicationdate[0]);
            queryWrapper.le("t1.applicationdate", applicationdate[1]);
        }
        return success(receiptService.listPage(MyBatisUtils.toPage(pageable), queryWrapper));

//        LambdaQueryChainWrapper<MaterialreceiptEntity> lambdaQuery = buildLambdaQuery(entity);
//        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
//        Page<MaterialreceiptEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
//        for (MaterialreceiptEntity record : page.getRecords()) {
//            try {
//                UserEntity userEntity = userService.getById(record.getReceipter());
//                record.setNickname(userEntity.getNickname());
//            } catch (Exception ignore) {
//                record.setReceipter(null);
//                record.setNickname("< 找不到领用人员 >");
//            }
//        }
//        for (MaterialreceiptEntity record : page.getRecords()) {
//            try {
//                OrganizationEntity organizationEntity = organizationService.getById(record.getDepartment());
//                System.out.println(organizationEntity);
//                record.setTitle(organizationEntity.getTitle());
//            } catch (Exception ignore) {
//                record.setDepartment(null);
//                record.setTitle("< 找不到部门 >");
//            }
//        }
//        for (MaterialreceiptEntity record : page.getRecords()) {
//            try {
//                MaterialSettingEntity materialSettingEntity = materialSettingService.getById(record.getMaterialId());
//                record.setMname(materialSettingEntity.getName());
//            } catch (Exception ignore) {
//                record.setMaterialId(null);
//                record.setMname("< 找不到物资 >");
//            }
//        }
//        for (MaterialreceiptEntity record : page.getRecords()) {
//            try {
//                UserEntity userEntity = userService.getById(record.getReviewer());
//                record.setUserReviewer(userEntity.getUsername());
//            } catch (Exception ignore) {
//                record.setReviewer(null);
//                record.setUserReviewer("< 找不到审核人员 >");
//            }
//        }
//        return success(page);
    }

    /**
     * 部门领导审核页面
     *
     * @param pageable
     * @param entity
     * @param applicationdate
     * @return
     */
    @GetMapping("/approvalList")
    public Object approvalList(@PageableDefault @SortDefault.SortDefaults({@SortDefault(sort = "id", direction = Sort.Direction.DESC)}) Pageable pageable, MaterialreceiptVO entity, Date[] applicationdate) {

        QueryWrapper<? extends MaterialreceiptEntity> queryWrapper = buildQueryApprovalList(entity);
        if (applicationdate != null && applicationdate.length == 2) {
            queryWrapper.ge("t1.applicationdate", applicationdate[0]);
            queryWrapper.le("t1.applicationdate", applicationdate[1]);
        }
        return success(receiptService.approvalListPage(MyBatisUtils.toPage(pageable), queryWrapper));
    }

    /**
     * 院办审核页面
     *
     * @param pageable
     * @param entity
     * @param applicationdate
     * @return
     */
    @GetMapping("/oapprovalList")
    public Object oapprovalList(@PageableDefault @SortDefault.SortDefaults({@SortDefault(sort = "id", direction = Sort.Direction.DESC)}) Pageable pageable, MaterialreceiptVO entity, Date[] applicationdate) {

        QueryWrapper<? extends MaterialreceiptEntity> queryWrapper = buildQueryOApprovalList(entity);
        if (applicationdate != null && applicationdate.length == 2) {
            queryWrapper.ge("t1.applicationdate", applicationdate[0]);
            queryWrapper.le("t1.applicationdate", applicationdate[1]);
        }
        return success(receiptService.oapprovalListPage(MyBatisUtils.toPage(pageable), queryWrapper));
    }

    /**
     * 获取一个 <strong>领用申请表</strong>
     *
     * @param id 主键ID
     */
    @GetMapping("{id}")
    public Object info(@PathVariable String id) {

//        return success(receiptService.getById(id));

        QueryWrapper<MaterialreceiptVO> wrapper = new QueryWrapper<>();
        wrapper.eq("t1.id", id);
        List<MaterialreceiptVO> records = receiptService.listPage(new Page<>(), wrapper).getRecords();
        if (records.isEmpty()) {
            return success(null);
        }
        return success(records.get(0));
    }

    @GetMapping("/approvalList/{id}")
    public Object approvalListPageinfo(@PathVariable String id) {

//        return success(receiptService.getById(id));

        QueryWrapper<MaterialreceiptVO> wrapper = new QueryWrapper<>();
        wrapper.eq("t1.id", id);
        List<MaterialreceiptVO> records = receiptService.approvalListPage(new Page<>(), wrapper).getRecords();
        if (records.isEmpty()) {
            return success(null);
        }
        return success(records.get(0));
    }

    @GetMapping("/oapprovalList/{id}")
    public Object oapprovalListPageinfo(@PathVariable String id) {

//        return success(receiptService.getById(id));

        QueryWrapper<MaterialreceiptVO> wrapper = new QueryWrapper<>();
        wrapper.eq("t1.id", id);
        List<MaterialreceiptVO> records = receiptService.oapprovalListPage(new Page<>(), wrapper).getRecords();
        if (records.isEmpty()) {
            return success(null);
        }
        return success(records.get(0));
    }

    /**
     * 添加一个 <strong>领用申请表</strong>
     *
     * @param entity 修改后的信息
     */
    @PostMapping
    public Object add(@RequestBody MaterialreceiptEntity entity, @NonNull Principal user) {
        receiptService.saveReceipt(entity, user);
        return success(entity);

//        HttpHeaders headers = new HttpHeaders();
//        headers.add(HttpHeaders.LOCATION, String.valueOf(entity.getId()));
//        return new ResponseEntity<>(headers, HttpStatus.CREATED);
    }

    /**
     * 修改一个 <strong>领用申请表</strong>
     *
     * @param id     主键ID
     * @param entity 修改后的信息
     */
    @PutMapping("{id}")
    public Object update(@PathVariable String id, @RequestBody MaterialreceiptEntity entity) {
        entity.setId(id);
        receiptService.updateReceipt(entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 删除一个 <strong>领用申请表</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        receiptService.deleteReceipt(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>领用申请表</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        receiptService.deleteReceipt(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<MaterialreceiptEntity> buildLambdaQuery(MaterialreceiptEntity entity) {
        LambdaQueryChainWrapper<MaterialreceiptEntity> lambdaQuery = receiptService.lambdaQuery();
        lambdaQuery.eq(entity.getId() != null, MaterialreceiptEntity::getId, entity.getId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getReceipter()), MaterialreceiptEntity::getReceipter, entity.getReceipter());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getDepartment()), MaterialreceiptEntity::getDepartment, entity.getDepartment());
        lambdaQuery.eq(entity.getApplicationdate() != null, MaterialreceiptEntity::getApplicationdate, entity.getApplicationdate());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getApplication()), MaterialreceiptEntity::getApplication, entity.getApplication());
        lambdaQuery.eq(entity.getDeliveryStatus() != null, MaterialreceiptEntity::getDeliveryStatus, entity.getDeliveryStatus());
        return lambdaQuery;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<MaterialreceiptEntity> buildQuery(MaterialreceiptVO entity) {
        QueryWrapper<MaterialreceiptEntity> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(entity.getReceipter()), "t1.receipter", entity.getReceipter());
        wrapper.like(StringUtils.isNotBlank(entity.getReceiptername()), "t2.name", entity.getReceiptername());
        wrapper.like(StringUtils.isNotBlank(entity.getDepartment()), "t1.department", entity.getDepartment());
        wrapper.like(StringUtils.isNotBlank(entity.getTitle()), "t3.title", entity.getTitle());
        wrapper.like(StringUtils.isNotBlank(entity.getDReviewer()), "t1.d_reviewer", entity.getDReviewer());
        wrapper.like(StringUtils.isNotBlank(entity.getDreviewerName()), "t4.name", entity.getDreviewerName());
        wrapper.like(StringUtils.isNotBlank(entity.getOReviewer()), "t1.o_reviewer", entity.getOReviewer());
        wrapper.like(StringUtils.isNotBlank(entity.getOreviewerName()), "t5.name", entity.getOreviewerName());
        wrapper.like(StringUtils.isNotBlank(entity.getDeliveryStatus()), "t1.delivery_status", entity.getDeliveryStatus());
        wrapper.like(StringUtils.isNotBlank(entity.getDApprovalStatus()), "t1.d_approval_status", entity.getDApprovalStatus());
        wrapper.like(StringUtils.isNotBlank(entity.getOApprovalStatus()), "t1.o_approval_status", entity.getOApprovalStatus());
        return wrapper;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<MaterialreceiptEntity> buildQueryApprovalList(MaterialreceiptVO entity) {
        QueryWrapper<MaterialreceiptEntity> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(entity.getReceipter()), "t1.receipter", entity.getReceipter());
        wrapper.like(StringUtils.isNotBlank(entity.getReceiptername()), "t2.name", entity.getReceiptername());
        wrapper.like(StringUtils.isNotBlank(entity.getDepartment()), "t1.department", entity.getDepartment());
        wrapper.like(StringUtils.isNotBlank(entity.getTitle()), "t3.title", entity.getTitle());
        wrapper.like(StringUtils.isNotBlank(entity.getDReviewer()), "t1.d_reviewer", entity.getDReviewer());
        wrapper.like(StringUtils.isNotBlank(entity.getDreviewerName()), "t4.name", entity.getDreviewerName());
        wrapper.like(StringUtils.isNotBlank(entity.getDeliveryStatus()), "t1.delivery_status", entity.getDeliveryStatus());
        wrapper.like(StringUtils.isNotBlank(entity.getDApprovalStatus()), "t1.d_approval_status", entity.getDApprovalStatus());
        return wrapper;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<MaterialreceiptEntity> buildQueryOApprovalList(MaterialreceiptVO entity) {
        QueryWrapper<MaterialreceiptEntity> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(entity.getReceipter()), "t1.receipter", entity.getReceipter());
        wrapper.like(StringUtils.isNotBlank(entity.getReceiptername()), "t2.name", entity.getReceiptername());
        wrapper.like(StringUtils.isNotBlank(entity.getDepartment()), "t1.department", entity.getDepartment());
        wrapper.like(StringUtils.isNotBlank(entity.getTitle()), "t3.title", entity.getTitle());
        wrapper.like(StringUtils.isNotBlank(entity.getDReviewer()), "t1.d_reviewer", entity.getDReviewer());
        wrapper.like(StringUtils.isNotBlank(entity.getDreviewerName()), "t4.name", entity.getDreviewerName());
        wrapper.like(StringUtils.isNotBlank(entity.getDeliveryStatus()), "t1.delivery_status", entity.getDeliveryStatus());
        wrapper.like(StringUtils.isNotBlank(entity.getDApprovalStatus()), "t1.d_approval_status", entity.getDApprovalStatus());
        return wrapper;
    }

    /**
     * 统计最大可领用数量
     * 现有库存-待出库数量（领用待审核数量）
     *
     * @param name
     * @return
     */
    @GetMapping("/getOptionalQuantity")
    public BigDecimal getOptionalQuantity(String name) {
        return receiptService.getOptionalQuantity(name);
    }

    /**
     * 获取部门领导、院办审核通过，未出库 的物资领用申请信息
     *
     * @param pageable
     * @return
     */
//    @GetMapping("/getMaterialreceiptPass")
//    public Object getMaterialreceiptPass(Pageable pageable) {
//        return success(receiptService.getMaterialreceiptPass(pageable));
//    }
    @GetMapping("/getMaterialreceiptPass")
    public Object getMaterialreceiptPass(@PageableDefault Pageable pageable, MaterialreceiptVO entity) {
        QueryWrapper<? extends MaterialreceiptEntity> queryWrapper = buildQuery(entity);
        return success(receiptService.getMaterialreceiptPass(MyBatisUtils.toPage(pageable), queryWrapper));
    }

    /**
     * 领用确认
     *
     * @param id
     * @param entity
     * @return
     */
    @PutMapping("/checkReceipt/{id}")
    public Object checkReceipt(@PathVariable String id, @RequestBody MaterialreceiptEntity entity) {
        receiptService.checkReceipt(id, entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}
